package com.hutao.manage.service.impl;

import java.sql.PreparedStatement;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hutao.manage.mapper.InterfaceAdmBloodMapper;
import com.hutao.manage.pojo.InterfaceAdmBlood;
import com.hutao.manage.service.BloodTypeService;
import com.hutao.manage.util.CacheJdbcUtil;
import com.hutao.manage.util.DateUtil;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@Service
public class BloodTypeServiceImpl implements BloodTypeService {

	private Logger logger = LoggerFactory.getLogger(BloodTypeServiceImpl.class);

	@Autowired
	private InterfaceAdmBloodMapper interfaceAdmBloodMapper;

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public String syncBloodType(String checkDate) {
		PreparedStatement ps = null;
		Connection con = null;
		ResultSet rs = null;
		try {
			con = CacheJdbcUtil.getConn();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("连接his的InterSystems Caché 数据库失败!失败原因:" + e.getMessage());
		}
		

		CallableStatement cs = null;
		List<InterfaceAdmBlood> interfaceAdmBloodList = new ArrayList<>();
		try {
			cs = con.prepareCall("{call web.DHCHisToOther_GetBloodGroupList(?)}");
			// 给存储过程的参数设置值
			cs.setString(1, checkDate);
			rs = cs.executeQuery();
			InterfaceAdmBlood interfaceAdmBlood = null;
			while (rs.next()) {
				interfaceAdmBlood = new InterfaceAdmBlood();
				String patientId = rs.getString("ADMID");// HIS内部标识/PatientId
				String patId = rs.getString("PATID");
				String name = rs.getString("NAME");
				String patNo = rs.getString("PATNO");
				String mrId = rs.getString("MEDNO");
				String onlyId = rs.getString("IPNo");
				String disDate = rs.getString("DISDATE");
				String type = rs.getString("TYPE");
				String bloodList = rs.getString("BLOODLIST");
				if(!"I".equals(type)) {
					continue;	
				}
				
				if(StringUtils.isEmpty(bloodList)) {
					continue;
				}
				
				if(bloodList.contains("型") && bloodList.contains("RH")) {
					String aboType = bloodList.split("型")[0];
					String aboCode = getAboType(aboType);
					
					String rhType = bloodList.split("型")[1].split("RH")[1];
					String rhCode = getRhType(rhType);
					
					interfaceAdmBlood.setMedicalClass("3");
					interfaceAdmBlood.setOrganization("山东省立医院");
					interfaceAdmBlood.setOrganizationId("49557184-0");
					interfaceAdmBlood.setMrId(StringUtils.isEmpty(mrId) ? null : mrId);
					interfaceAdmBlood.setName(StringUtils.isEmpty(name) ? null : name);
					interfaceAdmBlood.setOnlyId(StringUtils.isEmpty(onlyId) ? null : onlyId);
					interfaceAdmBlood.setPatId(StringUtils.isEmpty(patId) ? null : patId);
					interfaceAdmBlood.setPatientId(StringUtils.isEmpty(patientId) ? null : patientId);
					interfaceAdmBlood.setPatNo(StringUtils.isEmpty(patNo) ? null : patNo);
					if(StringUtils.isNotBlank(disDate)) {
						try {
							interfaceAdmBlood.setCheckTime(DateUtil.dateParse("yyyy-MM-dd HH:mm:ss", disDate));
						} catch (Exception e) {
							interfaceAdmBlood.setCheckTime(null);
							e.printStackTrace();
						}
						
					}

					interfaceAdmBlood.setBloodlist((StringUtils.isEmpty(bloodList) ? null : bloodList));
					interfaceAdmBlood.setSyncMed("1");
					interfaceAdmBlood.setAbo(aboCode);
					interfaceAdmBlood.setAboName(aboType);
					interfaceAdmBlood.setRh(rhCode);
					interfaceAdmBlood.setRhName(rhType);
					interfaceAdmBloodList.add(interfaceAdmBlood);
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("存储过程执行：call web.DHCHisToOther_GetBloodGroupList()失败!失败原因:"
					+ e.getMessage());
		}finally {
			// 关闭InterSystems Caché数据库连接
			try {
				if (rs != null)
					rs.close();
				if (ps != null)
					ps.close();
				if (con != null)
					con.close();
				logger.error("关闭InterSystems Caché数据库连接成功!");
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("关闭InterSystems Caché数据库连接失败，失败原因:" + e.getMessage());
			}
		}
		if (CollectionUtils.isEmpty(interfaceAdmBloodList)) {
			return "存储过程执行成功,数据为空!";
		}

		int updateCount = 0;
		int addCount = 0;
		
		for (InterfaceAdmBlood interfaceAdmIdInHos : interfaceAdmBloodList) {
			String patientId = interfaceAdmIdInHos.getPatientId();
			if(StringUtils.isNotBlank(patientId)) {
				List<InterfaceAdmBlood> oldInterfaceAdmBloods = interfaceAdmBloodMapper.selectByPatientId(patientId);
				if(CollectionUtils.isNotEmpty(oldInterfaceAdmBloods)) {
					updateCount++;
					for (InterfaceAdmBlood oldInterfaceAdmBlood : oldInterfaceAdmBloods) {
						oldInterfaceAdmBlood.setCheckTime(interfaceAdmIdInHos.getCheckTime());
						oldInterfaceAdmBlood.setBloodlist(interfaceAdmIdInHos.getBloodlist());
						oldInterfaceAdmBlood.setAbo(interfaceAdmIdInHos.getAbo());
						oldInterfaceAdmBlood.setAboName(interfaceAdmIdInHos.getAboName());
						oldInterfaceAdmBlood.setRh(interfaceAdmIdInHos.getRh());
						oldInterfaceAdmBlood.setRhName(interfaceAdmIdInHos.getRhName());
						interfaceAdmBloodMapper.updateByPrimaryKeySelective(oldInterfaceAdmBlood);
					}
				}else {
					interfaceAdmBloodMapper.insertSelective(interfaceAdmIdInHos);
					addCount++;
				}
			}
			
			
		}


		return "提取INTERFACE_ADM_BLOOD数据新增条数为:"+addCount+",更新条数为:" + updateCount;

	}
	
	public String getAboType(String aboType) {
		if("A".equals(aboType)) {
			return "1";
		}else if("B".equals(aboType)) {
			return "2";
		}else if("O".equals(aboType)) {
			return "3";
		}else if("AB".equals(aboType)) {
			return "4";
		}else {
			return "6";
		}
	}
	
	public String getRhType(String rhType) {
		if("阴性".equals(rhType)) {
			return "1";
		}else if("阳性".equals(rhType)) {
			return "2";
		}else {
			return "4";
		}
	}
	
	
	
	public static void main(String[] args) {
		String bloodType = "AB型RH阴性";
		System.out.println(bloodType.split("型")[0]);
		System.out.println(bloodType.split("型")[1].split("RH")[1]);
	}

}
